package com.nowcoder.Offer.List;

import org.junit.Test;

import java.util.ArrayList;

/**
 * 输入一个链表，按链表从尾到头的顺序返回一个ArrayList。
 */
public class ReverseListToArray {

    ArrayList<Integer> ans = new ArrayList<>();

    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ListNode prev = null;
        ListNode pNode = listNode;
        while(pNode!=null){
            ListNode next = pNode.next;
            pNode.next = prev;
            prev = pNode;
            pNode = next;
        }

        while(prev!=null){
            ans.add(prev.val);
            prev = prev.next;
        }
        return ans;
    }

    @Test
    public void test(){
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        printListFromTailToHead(node1).forEach(System.out::println);
    }


}
